package com.example.springscriptengine.js;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @program: cancan-java-share
 * @description: js工具
 * @author: czchen
 * @date: 2022-10-17 10:06:41
 */
public class JsUtil {
    /**
     * @param methodName js脚本方法名
     * @param script     js 脚本内容
     * @param args       js方法参数
     * @return
     * @throws ScriptException
     * @throws NoSuchMethodException
     */
    public static Object jsRun(String methodName, String script, Object... args) {
        try {
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            ScriptEngine javaScriptEngine = scriptEngineManager.getEngineByName("JavaScript");
            javaScriptEngine.eval(script);
            Invocable inv = (Invocable) javaScriptEngine;
            return inv.invokeFunction(methodName, args);
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
    }
}
